<template>
  <div class="page">
    <Cell title="头像" is-link :border="false">
      <template #value>
        <Image
          round
          width="2.5rem"
          height="2.5rem"
          fit="cover"
          position="center"
          :src="avatarVer(userInfo.avatar)"
        />
      </template>
    </Cell>
    <Cell
      title="姓名"
      :value="userInfo.nickName"
      is-link
      :border="false"
      @click="shopPopups.nickName = true"
    />
    <Cell title="手机号" :value="userInfo.userName" is-link :border="false" />
    <Cell
      title="性别"
      :value="sexShow(userInfo.sex)"
      is-link
      :border="false"
      @click="updateHandler('sex')"
    />
    <Button
      block
      round
      type="primary"
      style="position: absolute; bottom: 10px"
      @click="logOut"
      >退出登陆</Button
    >
    <!-- nickName -->
    <Dialog
      v-model:show="shopPopups.nickName"
      title="修改姓名"
      show-cancel-button
      @confirm="updateNickName()"
    >
      <Field label="姓名" placeholder="请输入姓名" v-model="nickNameInput" />
    </Dialog>

    <!-- sex -->
    <Popup round v-model:show="shopPopups.sex" position="bottom">
      <Picker
        :columns="sexColumns"
        @cancel="shopPopups.sex = false"
        @confirm="updateSex"
      />
    </Popup>
  </div>
</template>

<script lang="ts" setup>
import { updateUserProfile } from "@/api/user";
import router from "@/router";
import store from "@/store";
import {
  Button,
  Cell,
  Image,
  showFailToast,
  Popup,
  Picker,
  Field,
  Dialog,
} from "vant";
import { inject, reactive, ref } from "vue";
/** */
const avatarVer: any = inject("avatarVer");
const sexShow: any = inject("sexShow");
const sexColumns = [
  { text: "男", value: 0 },
  { text: "女", value: 1 },
];
/**用户信息 */
const userInfo = ref(store.state.userInfo);
const nickNameInput = ref(userInfo.value.nickName);
/**显示弹窗 */
const shopPopups = reactive({
  avatar: false,
  nickName: false,
  userName: false,
  sex: false,
});
/**退出登陆 */
const logOut = () => {
  store.dispatch("LogOut").then(() => {
    router.replace("/login");
  });
};
/**展示弹窗 */
const updateHandler = (key: string) => {
  shopPopups[key] = true;
};
/**
 * 修改性别
 */
const updateUserInfoByKey = (key: string, value: any) => {
  const data = {};
  data[key] = value;
  updateUserProfile(data)
    .then((_) => {
      refresh();
    })
    .catch(() => {
      showFailToast("修改失败");
    });
};
/**更新姓名 */
const updateNickName = () => {
  shopPopups.nickName = false;
  updateUserInfoByKey("nickName", nickNameInput.value);
};
/**更新性别 */
const updateSex = (selected: any) => {
  shopPopups.sex = false;
  updateUserInfoByKey("sex", selected.selectedOptions[0].value);
};
/**刷新信息 */
const refresh = () => {
  store.dispatch("GetUserInfo").then((_) => {
    userInfo.value = store.state.userInfo;
    nickNameInput.value = userInfo.value.nickName;
  });
};
</script>

<style lang="less" scoped>
.page {
  height: 100%;
}
</style>
